package cn.school;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import cn.school.util.DBUtil;

public class BankTransfer {

	public static void main(String[] args) {
		zhuanzhang("dxting", "laoliu", 400);
	}

	public static void zhuanzhang(String from, String to, int money) {
		Connection con = DBUtil.getConnection();
		PreparedStatement ps1 = null, ps2 = null;
		assert (con != null);
		String sql1 = "update bank set balance=balance-? where acno=?";
		String sql2 = "update bank set balance=balance+? where acno=?";
		try {
			con.setAutoCommit(false);// 关闭自动提交
			ps1 = con.prepareStatement(sql1);
			ps1.setInt(1, money);
			ps1.setString(2, from);
			int r1 = ps1.executeUpdate();
			ps2 = con.prepareStatement(sql2);
			ps2.setInt(1, money);
			ps2.setString(2, to);
			int r2 = ps2.executeUpdate();
			if (r1 == 0 || r2 == 0)
				con.rollback();// 回滚
			else
				con.commit();// 手工提交
		} catch (SQLException e) {
			try {// 有异常,强制回滚
				con.rollback();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close(ps1);
			DBUtil.close(ps2);
			DBUtil.close(con);
		}
	}

}
